import React, { useState } from 'react';
import { User } from '../../types';
import { useUsers, useSearch } from '../../hooks';
import { formatDate } from '../../utils';
import {
  Button,
  TextInput,
  Card,
  Modal,
  Container,
  Group,
  Stack,
  Text,
  Title,
  Avatar,
  ActionIcon,
  Box,
  Loader,
  Center,
  Alert,
  Grid,
  Badge
} from '@mantine/core';
import { IconSearch, IconMail, IconCalendar, IconEdit, IconTrash } from '@tabler/icons-react';
import UserForm from './UserForm';

interface UserListProps {
  onEditUser?: (user: User) => void;
}

const UserList: React.FC<UserListProps> = ({ onEditUser }) => {
  const { users, isLoading, error, deleteUser } = useUsers();
  const { query, setQuery, filteredItems } = useSearch(users, ['username', 'email', 'firstName', 'lastName']);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [userToDelete, setUserToDelete] = useState<User | null>(null);

  const handleEditUser = (user: User) => {
    if (onEditUser) {
      onEditUser(user);
    } else {
      setSelectedUser(user);
      setIsModalOpen(true);
    }
  };

  const handleCreateUser = () => {
    setSelectedUser(null);
    setIsModalOpen(true);
  };

  const handleDeleteClick = (user: User) => {
    setUserToDelete(user);
    setIsDeleteModalOpen(true);
  };

  const handleConfirmDelete = async () => {
    if (userToDelete) {
      try {
        await deleteUser(userToDelete.id);
        setIsDeleteModalOpen(false);
        setUserToDelete(null);
      } catch (error) {
        console.error('Failed to delete user:', error);
      }
    }
  };

  const handleCloseModal = () => {
    setIsModalOpen(false);
    setSelectedUser(null);
  };

  if (isLoading) {
    return (
      <Center h={200}>
        <Loader size="lg" />
      </Center>
    );
  }

  if (error) {
    return (
      <Alert color="red" title="错误">
        {error}
      </Alert>
    );
  }

  return (
    <Container size="xl">
      <Stack gap="lg">
        {/* Header */}
        <Group justify="space-between" align="flex-start">
          <Title order={1}>用户管理</Title>
          <Group gap="md">
            {/* Search */}
            <TextInput
              placeholder="搜索用户..."
              value={query}
              onChange={(e) => setQuery(e.currentTarget.value)}
              leftSection={<IconSearch size={16} />}
              w={300}
            />
            {/* Add User Button */}
            <Button onClick={handleCreateUser}>
              添加用户
            </Button>
          </Group>
        </Group>

        {/* User Grid */}
        <Grid>
          {filteredItems.map((user) => (
            <Grid.Col key={user.id} span={{ base: 12, sm: 6, md: 4 }}>
              <Card shadow="sm" padding="lg" radius="md" withBorder h="100%">
                <Group justify="space-between" mb="xs">
                  <Group>
                    <Avatar color="blue" radius="xl">
                      {(user.firstName || user.username || 'U').charAt(0)}{(user.lastName || user.email || 'S').charAt(0)}
                    </Avatar>
                    <Box>
                      <Text fw={500}>
                        {user.firstName && user.lastName ? `${user.firstName} ${user.lastName}` : user.username}
                      </Text>
                      <Text size="sm" c="dimmed">
                        @{user.username}
                      </Text>
                    </Box>
                  </Group>
                </Group>

                <Stack gap="xs" mb="md">
                  <Group gap="xs">
                    <IconMail size={16} />
                    <Text size="sm">{user.email}</Text>
                  </Group>
                  <Group gap="xs">
                    <IconCalendar size={16} />
                    <Text size="sm">{formatDate(user.createdAt)}</Text>
                  </Group>
                  <Box>
                    <Badge
                      size="sm"
                      color={
                        user.role === 'admin' ? 'red' :
                          user.role === 'moderator' ? 'yellow' : 'green'
                      }
                      variant="light"
                    >
                      {user.role}
                    </Badge>
                  </Box>
                </Stack>

                <Group justify="flex-end" gap="xs">
                  <ActionIcon
                    variant="light"
                    color="blue"
                    onClick={() => handleEditUser(user)}
                  >
                    <IconEdit size={16} />
                  </ActionIcon>
                  <ActionIcon
                    variant="light"
                    color="red"
                    onClick={() => handleDeleteClick(user)}
                  >
                    <IconTrash size={16} />
                  </ActionIcon>
                </Group>
              </Card>
            </Grid.Col>
          ))}
        </Grid>

        {
          filteredItems.length === 0 && (
            <Center py={60}>
              <Stack align="center" gap="md">
                <Box c="gray.5">
                  <svg width="48" height="48" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2M4 13h2m13-8l-4 4m0 0l-4-4m4 4V3" />
                  </svg>
                </Box>
                <Title order={3} c="gray.7">没有找到用户</Title>
                <Text c="gray.6" size="sm">
                  {query ? '尝试调整搜索条件' : '开始添加一些用户'}
                </Text>
              </Stack>
            </Center>
          )
        }

        {/* User Form Modal */}
        < Modal
          opened={isModalOpen}
          onClose={handleCloseModal}
          title={selectedUser ? '编辑用户' : '添加用户'}
          size="md"
        >
          <UserForm
            user={selectedUser}
            onSuccess={handleCloseModal}
            onCancel={handleCloseModal}
          />
        </Modal>

        {/* Delete Confirmation Modal */}
        <Modal
          opened={isDeleteModalOpen}
          onClose={() => setIsDeleteModalOpen(false)}
          title="确认删除"
          size="sm"
        >
          <Stack gap="md">
            <Text size="sm">
              确定要删除用户 <Text component="span" fw={500}>{userToDelete?.firstName && userToDelete?.lastName ? `${userToDelete.firstName} ${userToDelete.lastName}` : userToDelete?.username}</Text> 吗？此操作无法撤销。
            </Text>
            <Group justify="flex-end" gap="sm">
              <Button
                variant="default"
                onClick={() => setIsDeleteModalOpen(false)}
              >
                取消
              </Button>
              <Button
                color="red"
                onClick={handleConfirmDelete}
              >
                删除
              </Button>
            </Group>
          </Stack>
        </Modal>
      </Stack>
    </Container>
  );
};

export default UserList;